package gw.com.android.ui.system;

import android.content.Intent;
import android.os.Handler;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.gwtsz.gts2.hx.R;

import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.TagAliasCallback;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.presenter.http.HttpCallback;
import gw.com.android.presenter.http.MyConcernRequest;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.me_concern.AnalystData;
import gw.com.android.ui.me_concern.MyConcernActivity;
import gw.com.android.utils.PackStatis;
import www.com.library.app.Logger;

/**
 * @author jett
 * @since 2018-07-25.
 */
public class PushSettingActivity extends BaseActivity {

    private final int REQUEST_ANALYST = 16;

    @BindView(R.id.push_interact)
    View rlInteract;
    @BindView(R.id.push_analyst)
    View rlAnalyst;
    @BindView(R.id.push_quote_value)
    CheckBox cbQuote;
    @BindView(R.id.push_trade_value)
    CheckBox cbTrade;
    @BindView(R.id.push_system_value)
    CheckBox cbSystem;
    @BindView(R.id.push_interact_value)
    CheckBox cbInteract;
    @BindView(R.id.push_analyst_value)
    CheckBox cbAnalyst;
    @BindView(R.id.push_analyst_description)
    TextView tvAnalystDesc;

    private boolean hasFollow = false;
    private AtomicBoolean setChanged = new AtomicBoolean(false); // 当开关太频繁时，激光增删标签会失败，所以每隔5秒检查设置一次标签，退出当前页后设置一次标签
    private Handler mHandler = new Handler();
    private Runnable mTask;
    private MyConcernRequest concernRequest;

    @Override
    protected int getLayoutView() {
        return R.layout.activity_push_setting;
    }

    @Override
    protected void initLayoutView() {
        mTitleBar.setAppTitle(R.string.push_title);
        int accountType = GTConfig.instance().getAccountType();
        if (accountType == GTConfig.ACC_TYPE_GUEST) {
            rlInteract.setVisibility(View.GONE);
            rlAnalyst.setVisibility(View.GONE);
        } else if (accountType == GTConfig.ACC_TYPE_DEMO) {
            rlInteract.setVisibility(View.GONE);
            rlAnalyst.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initViewData() {
        cbQuote.setChecked(getState("quote"));
        cbQuote.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    setState("quote", true);
                } else {
                    setState("quote", false);
                }
            }
        });

        cbTrade.setChecked(getState("trade"));
        cbTrade.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    setState("trade", true);
                } else {
                    setState("trade", false);
                }
            }
        });

        cbSystem.setChecked(getState("system"));
        cbSystem.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    setState("system", true);
                } else {
                    setState("system", false);
                }
            }
        });

        cbInteract.setChecked(getState("interact"));
        cbInteract.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    setState("interact", true);
                } else {
                    setState("interact", false);
                }
            }
        });

        cbAnalyst.setChecked(getState("analyst"));
        cbAnalyst.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    setState("analyst", true);
                } else {
                    setState("analyst", false);
                }
            }
        });
        if (GTConfig.instance().getAccountType() != GTConfig.ACC_TYPE_REAL) {
            refreshAnalystDesc(true);
        } else {
            concernRequest = new MyConcernRequest();
            List<AnalystData> list = concernRequest.fetchFollowedAnalystLocal();
            refreshAnalystDesc(list != null && !list.isEmpty());
            loadAnalyst();
        }
        updateTag();
    }

    /**
     * 当开关太频繁时，激光增删标签会失败，所以每隔5秒检查设置一次标签，退出当前页后设置一次标签
     */
    private void updateTag() {
        if (mTask == null) {
            mTask = new Runnable() {
                @Override
                public void run() {
                    if (isFinishing()) {
                        return;
                    }
                    if (setChanged.get()) {
                        setChanged.set(false);
                        GTConfig.instance().setJpushAliasAndTags(new TagAliasCallback() {
                            @Override
                            public void gotResult(int i, String s, Set<String> set) {
                                Logger.i("jpush_tag_result", "i = " + i + "  s = " + s + "  set = " + set);
                                //Toast.makeText(PushSettingActivity.this, set.toString(), Toast.LENGTH_LONG).show();
                            }
                        }, null);
                    }
                    mHandler.postDelayed(this, 5000);
                }
            };
        }
        mHandler.postDelayed(mTask, 5000);
    }

    private void loadAnalyst() {
        if (concernRequest == null) {
            concernRequest = new MyConcernRequest();
        }
        concernRequest.getFollowedAnalystList(GTConfig.instance().mCurName, new HttpCallback<List<AnalystData>>() {
            @Override
            public void onSuccess(List<AnalystData> result) {
                refreshAnalystDesc(result != null && !result.isEmpty());
            }

            @Override
            public void onFailure(Exception e) {
            }
        });
    }

    private boolean getState(String key) {
        return GTConfig.instance().getPushState(key);
    }

    private void setState(String key, boolean state) {
        GTConfig.instance().setPushState(key, state);
        setChanged.set(true);
    }

    private void refreshAnalystDesc(boolean hasFollow) {
        this.hasFollow = hasFollow;
        if (hasFollow) {
            tvAnalystDesc.setText(R.string.push_analyst_desc);
            tvAnalystDesc.setTextColor(getResources().getColor(R.color.color_v));
        } else {
            tvAnalystDesc.setText(R.string.push_analyst_desc_empty);
            tvAnalystDesc.setTextColor(getResources().getColor(R.color.color_k));
        }
    }

    @OnClick(R.id.push_analyst_description)
    void toFollowAnalyst() {
        if (!hasFollow) {
            PackStatis.getToService("clickFollow", "Me", null, null);
            startActivityForResult(new Intent(getApplicationContext(), MyConcernActivity.class), REQUEST_ANALYST);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ANALYST) {
            loadAnalyst();
        }
    }

    @Override
    protected void onDestroy() {
        if (mTask != null && mHandler != null) {
            mHandler.removeCallbacks(mTask);
            mTask = null;
        }
        if (setChanged.get()) {
            AppMain.getApp().getHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    GTConfig.instance().setJpushAliasAndTags(null, null);
                }
            }, 2000);
        }
        super.onDestroy();
    }

}
